﻿<?php 
	session_start();
	require_once './model/user.php';
	
	// Clear all previous messages.
	if($_SESSION['log-err']) session_unregister('log-err');
	if($_SESSION['log-info']) session_unregister('log-info');
	
	// Chech whether cancel button is clicked.
	if(isset($_POST['cancelButton'])){
		$_SESSION['page'] = "home.php";
		header('Location: ../');
	}else{
		// Loading submitted parameters.
		$userName = $_POST['userName'];
		$userPassword = $_POST['userPassword'];
		$rePassword = $_POST['rePassword'];
		$userFullName = $_POST['userFullName'];
		$userRoleId = $_POST['userRoleId'];
		$userAddress = $_POST['userAddress'];
		$userLandPhone = $_POST['userLandPhone'];
		$userMobilePhone = $_POST['userMobilePhone'];
		$userEmail = $_POST['userEmail'];
		$userFax = $_POST['userFax'];
		
		// Check for mandatory fields.
		if($userName == "" || $userPassword == "" || $rePassword == "" || $userFullName == "" || $userRoleId < 1 || $userAddress == ""){
			$_SESSION['log-err'] = "අත්‍යවශ්‍ය තොරතුරු සම්පූර්ණ කර නොමැත.";
			$_SESSION['page'] = "addUser.php";
			header('Location: ../');
		}else{
			// Check whether the password and confirmation password matches.
			if($userPassword != $rePassword){
				$_SESSION['log-err'] = "Password and confirmation password mismatch";
				$_SESSION['page'] = "addUser.php";
				header('Location: ../');
			}
			
			require_once './model/dbconnection.php';
			$DB = new dbConnection();	
			
			// Check user exits (userName already taken).
			$userNameExits = mysql_query("SELECT * FORM users WHERE userName = '$userName'");
			if(mysql_num_rows($userNameExits) > 0){
				$_SESSION['log-err'] = "username already taken.";
				$_SESSION['page'] = "addUser.php";
				header('Location: ../');
			}else{
				mysql_query("BEGIN");
				$result;
				try{
					// Adding a user.
					$user = user::fillUser($userName, $userPassword, $userFullName, $userRoleId, $userAddress, $userLandPhone, $userMobilePhone, $userEmail, $userFax);
					$userId = $user->addUser();
					$result['addUser'] = ($userId > 0)?true:false;
					
					if(!in_array(false, $result)){
						// Commit queries.
						mysql_query("COMMIT");
						$_SESSION['log-info'] = "user සාර්ථකව ලියාපදිංචි කරන ලදි!";
						$_SESSION['page'] = "addUser.php";
						header('Location: ../');
					}else{
						// Rollback queries.
						mysql_query("ROLLBACK");
						$_SESSION['log-err'] = "සමාවන්න! ලියාපදිංචිය අසාර්ථක උනි.  els";
						$_SESSION['page'] = "addUser.php";
						header('Location: ../');
					}
				}catch(Exception $e){
					// Rollback queries.
					mysql_query("ROLLBACK");
					$_SESSION['log-err'] = "සමාවන්න! ලියාපදිංචිය අසාර්ථක උනි. ex";
					$_SESSION['page'] = "addUser.php";
					header('Location: ../');
				}
			}
		}
	}
?>